<template>
  <div v-show="playlist.length" class="player">
    <transition name="normal" @enter="enter" @after-enter="afterEnter" @leave="leave" @after-leave="afterLeave">
      <div v-show="fullScreen" class="normal-player">
        <!-- 背景 -->
        <div class="background">
          <img :src="currentSong.image" alt width="100%" height="100%" >
        </div>

        <!-- 头部title -->
        <div class="top">
          <div class="back" @click="back">
            <i class="icon-back"/>
          </div>
          <h1 class="title" v-html="currentSong.name"/>
          <h2 class="subtitle" v-html="currentSong.singer"/>
        </div>

        <!-- 中间CD旋转 -->
        <div class="middle" @touchstart.prevent="middleTouchStart" @touchmove.prevent="middleTouchMove" @touchend="middleTouchEnd">
          <div ref="middleL" class="middle-l">
            <!-- 控制异性动画 -->
            <div ref="cdWrapper" class="cd-wrapper">
              <!-- 控制CD旋转 动态添加类名 -->
              <div :class="cdCls" class="cd">
                <img :src="currentSong.image" alt class="image" >
              </div>
            </div>

            <div class="playing-lyric-wrapper">
              <div class="playing-lyric">{{ playingLyric }}</div>
            </div>
          </div>

          <!-- 歌词 -->
          <scroll ref="lyricList" :data="currentLyric && currentLyric.lines" class="middle-r">
            <div class="lyric-wrapper">
              <div v-if="currentLyric">
                <p v-for="(item, index) in currentLyric.lines" ref="lyricLine" :key="index" :class="{'current' : currentLineNum === index}" class="text">{{ item.txt }}</p>
              </div>
            </div>
          </scroll>
        </div>

        <!-- 底部按钮控件 -->
        <div class="bottom">
          <div class="dot-wrapper">
            <span :class="{'active' : currentShow === 'cd'}" class="dot"/>
            <span :class="{'active' : currentShow === 'lyric'}" class="dot"/>
          </div>
          <!-- 歌曲时间进度 -->
          <div class="progress-wrapper">
            <span class="time time-l">{{ format(this.currentTime) }}</span>
            <div class="progress-bar-wrapper">
              <progress-bar :percent="percent" @percentChange="onProgressBarChange"/>
            </div>
            <span class="time time-r">{{ format(this.currentSong.duration) }}</span>
          </div>
          <!-- 下一首 上一首 -->
          <div class="operators">
            <div class="icon i-left">
              <i :class="iconMode" @click="changeMode"/>
            </div>
            <div :class="disableCls" class="icon i-left">
              <i class="icon-prev" @click="prev"/>
            </div>
            <div :class="disableCls" class="icon i-center">
              <i :class="playIcon" @click="togglePlaying"/>
            </div>
            <div :class="disableCls" class="icon i-right">
              <i class="icon-next" @click="next"/>
            </div>
            <div class="icon i-right">
              <i :class="getFavoriteIcon(currentSong)" class="icon" @click="toggleFavorite(currentSong)"/>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <transition name="mini">
      <div v-show="!fullScreen" class="mini-player" @click="open">
        <div class="icon">
          <img :src="currentSong.image" :class="cdCls" alt width="40" height="40" >
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"/>
          <p class="desc" v-html="currentSong.singer"/>
        </div>
        <div class="control">
          <progress-circle :radius="radius" :percent="percent">
            <i :class="miniIcon" class="icon-mini" @click.stop="togglePlaying"/>
          </progress-circle>
        </div>
        <div class="control">
          <i class="icon-playlist" @click.stop="showPlayList"/>
        </div>
      </div>
    </transition>
    <playlist ref="playlist"/>
    <!-- 成功加载并且可以播放派发 canplay 事件 -->
    <!-- 加载失败或者发生错误会派发 error 事件 -->
    <!-- 播放歌曲的时候实时派发 timeupdate 事件可以获取当前播放时间 -->
    <!-- 歌曲播放完毕派发此事件 ended -->
    <audio ref="audio" :src="currentSong.url" @play="ready" @error="error" @timeupdate="updateTime" @ended="ended"/>
  </div>
</template>

<script type="text/ecmascript-6">
import { mapGetters, mapMutations, mapActions } from 'vuex'
import animations from 'create-keyframe-animation'
import { prefixStyle } from 'common/js/dom'
import ProgressBar from 'base/progress-bar/progress-bar'
import ProgressCircle from 'base/progress-circle/progress-circle'
import Lyric from 'lyric-parser' // 解决歌词
import Scroll from 'base/scroll/scroll'
import Playlist from 'components/playlist/playlist'
import { playMode } from 'common/js/config'
import { playerMixin } from 'common/js/mixin'
const transform = prefixStyle('transform')
const transitionDuration = prefixStyle('transitionDuration')
export default {
  mixins: [playerMixin],
  data () {
    return {
      songReady: false, // 歌曲加载完成旗帜
      currentTime: 0, // 播放时间  默认0
      radius: 32, // 环形进度条宽高
      currentLyric: null, // 歌词默认null
      currentLineNum: 0, // 当前歌词高亮行
      currentShow: 'cd',
      playingLyric: ''
    }
  },
  // mounted () {
  //   const { x, y, scale } = this._getPosAndScale()
  //   console.log(x, y, scale)
  // },
  created () {
    console.log(this.currentSong)
    this.touch = {}
  },
  methods: {
    // 用户点击缩小
    back () {
      this.setFullScreen(false)
    },
    // 用户点击放大
    open () {
      this.setFullScreen(true)
    },
    /**
       * el    作用元素DOM
       * done   回调函数
       */
    enter (el, done) {
      const { x, y, scale } = this._getPosAndScale()

      const animation = {
        0: {
          transform: `translate3d(${x}px, ${y}px, 0) scale(${scale})`
        },

        50: {
          transform: `translate3d(${x / 2}, ${y / 2}, 0) scale(1)`
        },

        100: {
          transform: `translate3d(0, 0, 0) scale(1)`
        }
      }

      // 3-配置
      animations.registerAnimation({
        // 取名字
        name: 'move',
        animation,
        presets: {
          duration: 400, // 持续时间
          easing: 'linear' // 缓动
        }
      })

      animations.runAnimation(this.$refs.cdWrapper, 'move', done)
    },
    afterEnter () {
      animations.unregisterAnimation('move')
      this.$refs.cdWrapper.style.animation = ''
    },
    leave (el, done) {
      this.$refs.cdWrapper.style.transition = 'all 0.4s'
      const { x, y, scale } = this._getPosAndScale()
      this.$refs.cdWrapper.style[transform] = `translate3d(${x}px, ${y}px, 0) scale(${scale})`
      this.$refs.cdWrapper.addEventListener('transitionend', done)
    },
    afterLeave () {
      this.$refs.cdWrapper.style.transition = ''
      this.$refs.cdWrapper.style[transform] = ''
    },
    _getPosAndScale () {
      // 小CD的宽度
      const targetWidth = 40
      // 目标距离左边距离
      const paddingLeft = 40
      // 目标距离底部距离
      const paddingBottom = 30
      // 大CD距离顶部距离
      const paddingTop = 80
      // 大CD宽度
      const width = window.innerWidth * 0.8
      // 计算放大比列
      const scale = targetWidth / width
      // X移动距离 因为是向右移动 所以是负数
      const x = -(window.innerWidth / 2 - paddingLeft)
      // Y移动距离
      const y = window.innerHeight - paddingBottom - paddingTop - width / 2

      return { x, y, scale }
    },
    // 用户点击暂停播放
    togglePlaying () {
      // 歌曲加载完毕才能点击暂停播放
      if (!this.songReady) {
        return false
      }
      this.setPlayingState(!this.playing)
      // 暂停歌词
      if (this.currentLyric) {
        this.currentLyric.togglePlay()
      }
    },
    // audio 成功加载完毕派发事件
    ready () {
      this.songReady = true
      this.savePlayHistory(this.currentSong)
    },
    // audio 加载失败派发事件
    error () {
      this.songReady = true
    },
    // audio   播放歌曲实时派发
    updateTime (e) {
      // console.log(e)
      this.currentTime = e.target.currentTime
    },
    // audio 歌曲播放完毕派发的事件
    ended (e) {
      // console.log('完毕')
      // 判断是什么播放模式
      if (this.mode === playMode.loop) {
        this.loop()
      } else {
        this.next()
      }
    },
    // 计算歌曲时间
    format (interval) {
      interval = Math.floor(interval)
      const minute = Math.floor(interval / 60)
      const second = this._pad(interval % 60, 2)
      return minute + ':' + second
    },
    // 秒 补位
    _pad (num, length) {
      let len = num.toString().length
      while (len < length) {
        num = '0' + num
        len++
      }
      return num
    },
    // 用户点击上一首
    prev () {
      if (!this.songReady) {
        return false
      }

      if (this.playlist.length === 1) {
        this.loop()
      } else {
        let index = this.currentIndex - 1
        if (index === -1) {
          index = this.playlist.length - 1
        }

        this.setCurrentIndex(index)

        if (!this.playing) {
          this.togglePlaying()
        }
      }

      this.songReady = false
    },
    // 用户点击下一首
    next () {
      // 判断是否成功加载
      if (!this.songReady) {
        return false
      }
      // 如果 playlist 只有一首歌曲 currentSong 逻辑就不会执行
      // 判断
      if (this.playlist.length === 1) {
        this.setPlayingState(!this.playing)
        this.loop()
        return false
      } else {
        let index = this.currentIndex + 1
        if (index === this.playlist.length) {
          index = 0
        }
        this.setCurrentIndex(index)
        if (!this.playing) {
          this.togglePlaying()
        }
      }

      // 成功加载完毕 重置 false
      this.songReady = false
    },
    loop () {
      this.$refs.audio.currentTime = 0
      this.$refs.audio.play()

      // 循坏播放的话我们就把歌词进度调整为0
      if (this.currentLyric) {
        this.currentLyric.seek(0)
      }
    },
    onProgressBarChange (percent) {
      // 接受传递过来的进度条百分比
      // console.log(percent)
      const currentTime = this.currentSong.duration * percent
      this.$refs.audio.currentTime = currentTime
      if (!this.playing) {
        this.togglePlaying()
      }

      if (this.currentLyric) {
        this.currentLyric.seek(currentTime * 1000)
      }
    },
    // 歌词函数
    getLyric () {
      // 对象.方法
      this.currentSong.getLyric()
        .then(result => {
        // console.log(result)
        // 如果当前歌词不是当前歌词。。
          if (this.currentSong.lyric !== result) {
            return false
          }
          // 就是一个 new Lyric 实列对象
          // handleLyric 函数 这个回调函数就是歌词每一行发生改变 去毁掉一下
          this.currentLyric = new Lyric(result, this.handleLyric)
          // console.log(this.currentLyric)
          // 歌曲播放的时候调用该方法
          if (this.playing) {
            this.currentLyric.play()
          }
        })
        .catch(() => {
          this.currentLyric = null
          this.playingLyric = ''
          this.currentLineNum = 0
        })
    },

    handleLyric ({ lineNum, txt }) {
      // console.log(lineNum, txt)
      this.currentLineNum = lineNum
      this.playingLyric = txt
      if (lineNum > 5) {
        // 大于5行 滚动到指定元素
        // -5 保证在屏幕中间
        const lineEl = this.$refs.lyricLine[lineNum - 5]
        this.$refs.lyricList.scrollToElement(lineEl, 1000)
      } else {
        // 否则不改变
        this.$refs.lyricList.scrollTo(0, 0, 1000)
      }
    },
    middleTouchStart (event) {
      // 手指触摸屏幕触发
      // console.log(event)
      // 初始化完毕旗帜 表示已经初始化完毕
      this.touch.initiated = true
      // 记录手指点击的为位置 手指触摸屏幕位置
      // X坐标
      this.touch.startX = event.touches[0].clientX
      // Y坐标
      this.touch.startY = event.touches[0].clientY
    },
    middleTouchMove (event) {
      // 手指在屏幕滑动触发
      // console.log(event)
      // 判断是否已经初始化
      if (!this.touch.initiated) {
        return false
      }

      const deltaX = event.touches[0].clientX - this.touch.startX
      const deltaY = event.touches[0].clientY - this.touch.startY
      // console.log(Math.abs(deltaX), Math.abs(deltaY))
      if (Math.abs(deltaY) > Math.abs(deltaX)) {
        // 表示用户手指上滑或者下滑
        return false
      }
      // 如果 currentShow = cd 的话 也就是说当前显示的是cd 那么歌词的偏移就是负的屏幕宽度
      const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
      // 计算手指滑动的距离  初始化的时候只能从右往左滑动
      const offsetWidth = Math.min(
        0,
        Math.max(-window.innerWidth, left + deltaX)
      )
      // console.log(deltaX, left, offsetWidth)
      // 计算发动百分比
      this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
      this.$refs.lyricList.$el.style[transform] = 'translate3d(' + offsetWidth + 'px, 0, 0)'
      // move 需要设置为0
      this.$refs.lyricList.$el.style[transitionDuration] = 0

      this.$refs.middleL.style.opacity = 1 - this.touch.percent
      this.$refs.middleL.style[transitionDuration] = 0
    },
    middleTouchEnd (event) {
      // 手指离开屏幕触发
      let offsetWidth
      let opacity
      // 从右往左滑动
      if (this.currentShow === 'cd') {
        if (this.touch.percent > 0.1) {
          offsetWidth = -window.innerWidth
          this.currentShow = 'lyric'
          opacity = 0
        } else {
          offsetWidth = 0
          opacity = 1
        }
      } else if (this.currentShow === 'lyric') {
        // 从左往右滑动
        if (this.touch.percent < 0.9) {
          offsetWidth = 0
          this.currentShow = 'cd'
          opacity = 1
        } else {
          offsetWidth = -window.innerWidth
          opacity = 0
        }
      }
      const time = 400
      // 过渡效果
      this.$refs.lyricList.$el.style[transform] = 'translate3d(' + offsetWidth + 'px, 0, 0)'
      // 这样子写也可以
      // this.$refs.lyricList.$el.style.transition = 'all .4s'
      this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
      // 过度透明度
      this.$refs.middleL.style.opacity = opacity
      this.$refs.middleL.style[transitionDuration] = `${time}ms`
    },
    showPlayList () {
      this.$refs.playlist.show()
    },
    ...mapMutations({
      setFullScreen: 'SET_FULL_SCREEN'
    }),
    ...mapActions(['savePlayHistory'])
  },
  computed: {
    // 底部播放器 播放暂停图标
    playIcon () {
      return this.playing ? 'icon-pause' : 'icon-play'
    },
    // 迷你播放器 播放暂停图标
    miniIcon () {
      return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
    },
    // 计算是播放还是暂停 控制CD是否旋转
    cdCls () {
      return this.playing ? 'play' : 'play pause'
    },
    disableCls () {
      // 歌曲没有加载完毕给一个样式
      return this.songReady ? '' : 'disable'
    },
    // 计算播放时长的百分比
    percent () {
      return this.currentTime / this.currentSong.duration
    },
    ...mapGetters(['fullScreen', 'currentIndex'])
  },
  watch: {
    // 暂停播放 点击播放模式会继续播放 我们可以进行判断
    currentSong (newSong, oldSong) {
      if (!newSong.id) {
        return false
      }
      // 切换播放模式时歌曲播放状态不能改变
      if (newSong.id === oldSong.id) {
        return false
      }
      if (this.currentLyric) {
        // 连续快速点击歌词会出现混乱 要把之前的停止
        this.currentLyric.stop()
        this.currentTime = 0
        this.playingLyric = ''
        this.currentLineNum = 0
      }

      clearTimeout(this.time)
      this.time = setTimeout(() => {
        // 确保只执行一次
        this.$refs.audio.play()
        // 歌曲改变调用歌词函数
        this.getLyric()
      }, 1000)
    },
    playing (newPlaying) {
      this.$nextTick(() => {
        newPlaying ? this.$refs.audio.play() : this.$refs.audio.pause()
      })
    }
  },
  components: { ProgressBar, ProgressCircle, Scroll, Playlist }
}
</script>

<style lang="stylus" scoped rel="stylesheet/stylus">
  @import '~common/stylus/variable';
  @import '~common/stylus/mixin';

  .player {
    .normal-player {
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: $color-background;
      z-index 150;

      &.normal-enter-active, &.normal-leave-active {
        transition: all 0.4s;

        .top, .bottom {
          transition: all 0.4s;
        }
      }

      &.normal-enter, &.normal-leave-to {
        opacity: 0;

        .top {
          transform: translate3d(0, -100px, 0);
          // transform scale(4);
        }

        .bottom {
          transform: translate3d(0, 100px, 0);
          // transform scale(4);
        }
      }

      .background {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
        z-index: -1;
        filter: blur(20px);
        opacity: 0.4;
      }

      .top {
        position: relative;

        .back {
          position: absolute;
          top: 0;
          left: 0;

          .icon-back {
            display: inline-block;
            font-size: $font-size-large-x;
            padding: 10px;
            color: $color-theme;
            transform: rotate(-90deg);
          }
        }

        .title {
          width: 70%;
          margin: 0 auto;
          height: 42px;
          line-height: 42px;
          text-align: center;
          letter-spacing: 2px;
          font-weight: bold;
          no-wrap();
        }

        .subtitle {
          width: 100%;
          text-align: center;
          font-size: $font-size-medium;
          letter-spacing: 2px;
          no-wrap();
        }
      }

      .middle {
        position: fixed;
        width: 100%;
        top: 80px;
        bottom: 170px;
        white-space: nowrap;
        font-size: 0;

        .middle-l {
          display: inline-block;
          vertical-align: top;
          position: relative;
          width: 100%;
          height: 0;
          padding-top: 80%;

          .cd-wrapper {
            position: absolute;
            left: 10%;
            top: 0;
            width: 80%;
            height: 100%;

            .cd {
              width: 100%;
              height: 100%;
              box-sizing: border-box;
              border: 10px solid rgba(255, 255, 255, 0.1);
              border-radius: 50%;

              .image {
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                border-radius: 50%;

              }

              &.play {
                animation: rotate 20s linear infinite;
              }

              &.pause {
                animation-play-state: paused;
              }
            }
          }

          .playing-lyric-wrapper {
            width: 80%;
            margin: 30px auto 0 auto;
            overflow: hidden;
            text-align: center;

            .playing-lyric {
              height: 20px;
              line-height: 20px;
              font-size: $font-size-medium;
              color: $color-theme;
              font-weight bold;
            }
          }
        }

        .middle-r {
          display: inline-block;
          vertical-align: top;
          width: 100%;
          height: 100%;
          overflow: hidden;

          .lyric-wrapper {
            width: 80%;
            margin: 0 auto;
            overflow: hidden;
            text-align: center;

            .text {
              line-height: 32px;
              color: $color-text-l;
              font-size: $font-size-medium;

              &.current {
                color: $color-theme;
              }
            }
          }
        }
      }

      .bottom {
        position: absolute;
        bottom: 50px;
        width: 100%;

        .dot-wrapper {
          width: 100%;
          display: flex;
          justify-content: center;

          .dot {
            display: inline-block;
            width: 8px;
            height: 8px;
            background-color: $color-text-l;
            border-radius: 50%;
          }

          .active {
            width: 20px;
            border-radius: 10px;
            background-color: rgba(255, 255, 255, 0.8);
          }

          .dot:first-child {
            margin-right: 8px;
          }
        }

        .progress-wrapper {
          display: flex;
          align-items: center;
          width: 80%;
          margin: 0px auto;
          padding: 10px 0;

          .time {
            color: $color-text;
            font-size: $font-size-small;
            flex: 0 0 30px;
            line-height: 30px;
            width: 30px;

            &.time-l {
              text-align: left;
            }

            &.time-r {
              text-align: right;
            }
          }

          .progress-bar-wrapper {
            flex: 1;
          }
        }

        .operators {
          display: flex;
          align-items: center;
          padding: 0 10px;

          .icon {
            flex: 1;
            text-align: center;
            color: $color-theme;
            font-size: 30px;
            .icon-favorite{
              color $color-sub-theme;
            }
          }

          .i-center {
            font-size: 40px;
          }

          .disable {
            color: $color-theme-d;
          }
        }
      }
    }

    .mini-player {
      position: fixed;
      bottom: 0;
      width: 100%;
      height: 60px;
      display: flex;
      align-items: center;
      z-index: 180;
      background-color: $color-highlight-background;

      &.mini-enter-active, &.mini-leave-active {
        transition: all 0.4s;
      }

      &.mini-enter, &.mini-leave-to {
        transform: translate3d(0, 100px, 0);
      }

      .icon {
        width: 40px;
        padding: 0 10px 0 20px;

        img {
          border-radius: 50%;

          &.play {
            animation: rotate 20s 0s linear infinite;
          }

          &.pause {
            animation-play-state: paused;
          }
        }
      }

      .text {
        flex: 1;
        overflow: hidden;
        height: 40px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;

        .name {
          font-size: $font-size-medium;
          font-weight: bold;
          display: -webkit-box;
          overflow: hidden;
          white-space: normal !important;
          text-overflow: ellipsis;
          word-wrap: break-word;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .desc {
          font-size: $font-size-small;
          color: $color-text-d;
          font-weight: bold;
          display: -webkit-box;
          overflow: hidden;
          white-space: normal !important;
          text-overflow: ellipsis;
          word-wrap: break-word;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }

      .control {
        width: 30px;
        padding: 0 10px;
        flex: 0 0 30px;

        .icon-play-mini, .icon-pause-mini, .icon-playlist {
          font-size: 30px;
          color: $color-theme-d;
        }
      }

      .icon-mini {
        position: absolute;
        top: 1px;
        left: 1px;
        width: 32px;
        height: 32px;
      }
    }

    @keyframes rotate {
      0% {
        transform: rotate(0);
      }

      50% {
        transform: rotate(180deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  }
</style>
